from PyQt4.QtGui import QWidget,QTreeView,QStandardItemModel,QStandardItem,QBrush,QColor,QFont,QSortFilterProxyModel,QItemSelection,QItemSelectionModel
from PyQt4 import QtCore
from PyQt4.QtCore import QString,Qt,QVariant,QStringList
from KTrade import *
import xml.etree.ElementTree as ET
import sys,importlib

class KStrategyTreeWidget(QTreeView):
	''' The UI of strategy batch test '''
	def __init__(self, parent=None):
		super(KStrategyTreeWidget, self).__init__(parent)
		
		# setup model
		tmodel=KStrategyTreeModel(self)
		self.setModel(tmodel)
		tmodel.UpdateStrategyList()
		
		# setup view
		self.setColumnWidth(0,150)
		self.expandAll()
		self.setSortingEnabled(True)
		self.setSelectionBehavior(self.SelectRows)
		self.setSelectionMode(self.SingleSelection)
		self.setEditTriggers(self.NoEditTriggers)
		
		mselectmodel=QItemSelectionModel(tmodel)
		#select first strategy by default
		parentitem=self.model().item(0,0)		
		mselectmodel.select(parentitem.child(0,0).index(),QItemSelectionModel.Select)
		self.setSelectionModel(mselectmodel)
	
	def GetSelectedStrategyClass(self):
		# get the selected strategy class
		index = self.selectedIndexes()[0]
		mitem = index.model().itemFromIndex(index)
		modulename=str(mitem.data(Qt.UserRole).toString())
		
		(temp,classname)=modulename.split('.',1)
		
		aMod =  importlib.import_module(modulename) #load module
		aClass= getattr(aMod, classname) #load class
		return aClass

	

class KStrategyTreeModel(QStandardItemModel):
	def __init__(self, parent=None):
		super(KStrategyTreeModel, self).__init__(parent)
		self.txtfont=QFont("Times", 11)


	def data(self,index,role):
		# overide
		if role==Qt.FontRole:
			return self.txtfont
		else:
			return QStandardItemModel.data(self,index,role)

	def OnSetupColumns(self):
		#called when setting up columns
		HeaderLabels=['Name','Summary']
		self.setColumnCount(2)
		for each_index in range(0,len(HeaderLabels)):
			self.setHeaderData(each_index, Qt.Horizontal,QString(HeaderLabels[each_index]))	
		ColNames=['name','summary']
		return ColNames

	def UpdateStrategyList(self):
	# build the model with specified fields		
		self.clear()
		ColNames=self.OnSetupColumns()
		pathname=r'D:\Dropbox\Trading2013\KunTrading\ConfigFiles\KStrategyList.xml'
		tree = ET.parse(pathname)
		root = list(tree.getroot())
		rowindex=0
	
		for child in root:  # for each strategy folder
			mitem=QStandardItem()
			mitem.setData(child.get('name'),Qt.DisplayRole)
			self.setItem(rowindex, 0, mitem);	
			subrowindex=0
			for each_strat in child: # for each strategy
				colindex=0
				for each_col in ColNames:
					subitem=QStandardItem()
					mitem.setChild(subrowindex,colindex,subitem)
					subitem.setData(each_strat.find(each_col).text.strip("\""),Qt.DisplayRole)
					subitem.setData(each_strat.find('class').text.strip("\""),Qt.UserRole)
					#subitem.setData("test",Qt.DisplayRole)
					#self.setItem(rowindex, colindex, subitem);	
					colindex+=1
				subrowindex+=1
			rowindex+=1	






